#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms
import django
import djangoproject
import COOPIP_Ajax
import COOPIP_Misc
import COOPIP_Form, COOPIP_DynamicTemplate, COOPIP_Authentication, COOPIP_FormIntranet
import COOPIP_FormGeneral, COOPIP_FormCISReport, COOPIP_FormMeterPing
from django.db import transaction #see django bug #9964; these pages are SELECT only, so turnin over to autocommit shouldn't cause issues
import AMR, GOS, GIS, CIS




def MainMenu(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)
    if(not Permission): 
        return DefaultMainPage(LoginStatus)  
    t = loader.get_template('/opt/coopip/djangoproject/templates/meterpingmainmenu.html')
    c = Context({'Permission': Permission})
    return HttpResponse(t.render(c))



def MeterPingDispatch(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)
    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    form=COOPIP_Form.LoginForm()
    Yesterday=datetime.datetime.now() - datetime.timedelta(days=1)
    OpenLayersJavaScriptHeading=COOPIP_Ajax.GetOpenLayersJavaScriptHeading()
    OpenLayersJavaScript=COOPIP_Ajax.GetOpenLayersJavaScript()
    FailedMeters=Meter.objects.filter(Symbology='failed').order_by('-LastSuccessfulPingDateTime')
    ActiveButNotAuthorizedMeters=Meter.objects.filter(Symbology='activebutnotauthorized').filter(CISIdleIndicator=True).order_by('-LastSuccessfulPingDateTime')
    NotFoundMeters=Meter.objects.filter(Symbology='activebutnotauthorized').exclude(CISIdleIndicator=True).order_by('-LastSuccessfulPingDateTime') 
    ServiceOrderMeters=Meter.objects.filter(Symbology='serviceorder').order_by('-LastSuccessfulPingDateTime')

    InvestigationMeters=Meter.objects.filter(Symbology='investigation').order_by('-InvestigationStartDateTime') | Meter.objects.filter(Description__isnull=False).exclude(Description='').order_by('id')
    #raise(str(InvestigationMeters))
    form=COOPIP_Form.BuildAndProcessMeterForm(request,  FailedMeters, ActiveButNotAuthorizedMeters, NotFoundMeters, ServiceOrderMeters, InvestigationMeters)
    COOPIP_DynamicTemplate.UpdateDispatchMeterPingTemplate(FailedMeters, ActiveButNotAuthorizedMeters, NotFoundMeters, ServiceOrderMeters, InvestigationMeters, Username)
    form = COOPIP_Form.PopulateMeterForm(form, FailedMeters, ActiveButNotAuthorizedMeters, NotFoundMeters, ServiceOrderMeters, InvestigationMeters)

    form.setData(form.data)
    t = loader.get_template('/opt/coopip/djangoproject/templates/dynamic_dispatchmeterping' + Username + '.html')
    c = Context({'OpenLayersJavaScript': OpenLayersJavaScript,
                 'OpenLayersJavaScriptHeading': OpenLayersJavaScriptHeading,
                 'form': form})
    return HttpResponse(t.render(c))



def Configuration(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)

    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    form=COOPIP_Form.LoginForm()
    Report='Placeholder for the meter ping report'
    form=COOPIP_Form.BuildDynamicForm(request, 'MeterPingConfiguration')
    COOPIP_FormMeterPing.ProcessMeterPingConfigurationtForm(form, Username, request)
    form = COOPIP_FormMeterPing.PopulateMeterPingConfigurationForm(form)

    MeterPingRate=[djangoproject.models.ipbase.COOPIPSetting.GetPingRate()]
    
    Report='\n'.join(MeterPingRate)
     

    t = loader.get_template('/opt/coopip/djangoproject/templates/meterpingconfiguration.html')
    c = Context({'form': form, 'Report': Report, 'Permission': Permission})
    return HttpResponse(t.render(c))





def MeterPingReport(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)

    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    form=COOPIP_Form.LoginForm()
    Report='Placeholder for the meter ping report'
    form=COOPIP_Form.BuildDynamicForm(request, 'MeterPingReport')
    MeterPings=COOPIP_FormIntranet.ProcessMeterPingReportForm(form, Username, request)
    Results=[]
    try: 
        Results.append(djangoproject.models.ipbase.MeterPing.objects.all()[1].GetHeadings())
    except IOError:
        pass
    for ping in MeterPings:
        Results.append(str(ping))
    Report='\n'.join(Results)
     
    #form = COOPIP_Form.PopulateMeterPingReportForm(form)
    #raise(Exception('Here'))
    t = loader.get_template('/opt/coopip/djangoproject/templates/meterpingreport.html')
    c = Context({'form': form, 'Report': Report, 'Permission': Permission})
    return HttpResponse(t.render(c))


def DefaultMainPage(LoginStatus):
    form=COOPIP_Form.LoginForm()
    t = loader.get_template('/opt/coopip/djangoproject/templates/intranetmainpage.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form})
    return HttpResponse(t.render(c))


def StringMeterNumber(meter):
    if('incident' in meter.IncidentSymbology.lower()):
        return 'I-' + str(meter.SerialNumber)
    else:
        return meter.SerialNumber

def StringLastResponse(meter):
    if(meter.IncidentSymbology in ['success', 'open_incident']):
        return 'success'
    elif(meter.IncidentSymbology in ['failed', 'failed_with_open_incident']):
        return 'fail'
    elif(meter.IncidentSymbology in ['activebutnotauthorized']):
        return 'success, not authorized'
    else:
        return meter.IncidentSymbology







def MeterPingDisplayAMRFailure(request):
    return MeterPingDisplay(request, AMRFailureIndicator=True)

def MeterPingDisplaySubstationFailure(request):
    return MeterPingDisplay(request, SubstationFailureIndicator=True)





def BlinkCountReport(request):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_Editor_Technology', 'COOPIP_Editor_Operations'])
    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    #When using authentication, check for application permission here.
    import datetime
    #Meter Blink Tasks needed
    #Run MeterBlinkCounts only on new dates (Change************, select the last one with a count to be the starting point)
    #Review Flag Meter Blinks code Before running it, should be ok
    #Create a MeterBlinkReport View
    #Headings:
    #MeterNumber        MeterBlink30        MeterBlink60         MeterBlink90   MeterBlink180      MeterBlink360
    #Add these as database fields to the SerialNumber table, so that they can be precalculated, plus add a MeterBlinkFlagLastCalculateDate????
    #Create a Detail View
    #Meter Number, Total Blinks, Calculated Blinks, Date, Flag Indicator [Show all blinks for the meter, in reverse date order]
    Report=[]
    Report.append('Meter'.ljust(20) + '30 Days'.ljust(10) + '60 Days'.ljust(10) + '90 Days'.ljust(10) + '180 Days'.ljust(10) + '360 Days'.ljust(10))
    Meters=Meter.objects.all().order_by('SerialNumber')
    for meter in Meters:
        Report.append(str(meter.SerialNumber).ljust(20) + str(meter.MeterBlink30).ljust(10) + str(meter.MeterBlink60).ljust(10) +\
                      str(meter.MeterBlink90).ljust(10) + str(meter.MeterBlink180).ljust(10) + \
                      str(meter.MeterBlink360).ljust(10))  
    Report='\n'.join(Report)      
    t = loader.get_template('/opt/coopip/djangoproject/templates/genericreporttemplate.html')
    c = Context({'Report': Report})
    return HttpResponse(t.render(c))


def BlinkCountReportDetail(request, MeterNumber):
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, djangoproject.settings.StatusGroups)
    if(not Permission): 
        return DefaultMainPage(LoginStatus)
    #When using authentication, check for application permission here.
    import datetime
    #Meter Blink Tasks needed
    #Run MeterBlinkCounts only on new dates (Change************, select the last one with a count to be the starting point)
    #Review Flag Meter Blinks code Before running it, should be ok
    #Create a MeterBlinkReport View
    #Headings:
    #MeterNumber        MeterBlink30        MeterBlink60         MeterBlink90   MeterBlink180      MeterBlink360
    #Add these as database fields to the SerialNumber table, so that they can be precalculated, plus add a MeterBlinkFlagLastCalculateDate????
    #Create a Detail View
    #Meter Number, Total Blinks, Calculated Blinks, Date, Flag Indicator [Show all blinks for the meter, in reverse date order]
    Report=[]
    Report.append('Meter'.ljust(20) + 'Total Blinks'.ljust(10) + 'Calculated Blinks'.ljust(10) + 'Flag'.ljust(10))
    MeterBlinks=MeterBlink.objects.filter(SerialNumber=MeterNumber)
    for meterBlink in MeterBlinks:
        Report.append(str(MeterNumber).ljust(20) + str(meterBlink.Count).ljust(10) + str(CalculatedBlinks).ljust(10) + str(meter.FlagIndicator).ljust(10))                  
    t = loader.get_template('/opt/coopip/djangoproject/templates/genericreporttemplate.html')
    c = Context({'form': form, 'Report': Report})
    return HttpResponse(t.render(c))



def ClearAMRTctInpq(request):

    GenericReportTitle = "Clear AMR TctInpq View"
    GenericMessage = "Should be called from the AMR Server when teh TCTSvr or TCTRSvr service crashes."
    Preformatted=[]
    Preformatted.append('Start Count:  ' + str(AMR.TctInpq.objects.count()))
    AMR.TctInpq.objects.all().delete()
    django.db.connections['amr'].commit()
    Preformatted.append('End Count:  ' + str(AMR.TctInpq.objects.count()))
    Preformatted = '\n'.join(Preformatted)
    t = loader.get_template('/opt/coopip/djangoproject/templates/genericreporttemplate.html')
    c = Context({'Preformatted': Preformatted, 'GenericReportTitle': GenericReportTitle, 'GenericMessage': GenericMessage})
    return HttpResponse(t.render(c))












